import threading

from ...conf import settings
from .custom_redis_queue import RedisQueue
from .process_queue_message import process_messages

generate_result_list = settings.GENERATE_TOPIC_LIST
group = settings.GENERATE_GROUP
generate_request_topic = settings.GENERATE_REQUEST

redis_conf = {
    'host': settings.REDIS_HOST,
    'port': settings.REDIS_PORT,
    'password': settings.REDIS_PASSWORD,
    'db': 0,
}


def start_client():
    return RedisQueue(redis_conf)


redis_client = start_client()


def sub():
    """
    订阅消息
    """

    redis_client.loop_listen(process_messages, group, generate_result_list, clean=False)


def start_redis_consumer():
    """
    启动守护线程
    """
    t = threading.Thread(target=sub)
    t.daemon = True
    t.start()


consumer = start_redis_consumer()


def redis_queue_send_message(data, topic=generate_request_topic):
    """
    发送消息
    """
    redis_client.send_msg(topic, data)


def get_redis_queue_length(topic=generate_request_topic):
    """
    获取队列长度
    """
    return redis_client.queue_len(topic)




# # 创建一个消费者
# redis_consumer = redis.StrictRedis(**redis_conf)
#
# try:
#     # 创建订阅组
#     redis_consumer.xgroup_create(generate_topic, group, id='0', mkstream=True)
# except:
#     pass
#
#
# def sub():
#     """
#     订阅消息
#     """
#     print('start redis consumer')
#     while True:
#         # messages = redis_consumer.xread({generate_topic: '0'}, block=0)  # Block until a new message arrives
#         messages = redis_consumer.xreadgroup(group, 'consumer', {generate_topic: '>'}, block=0, count=1)
#         for stream, message_list in messages:
#             for message_id, message_data in message_list:
#                 # Process the message
#                 process_messages(message_data)
#                 # print(f"Received message: {message_data}")
#                 # Acknowledge the message by removing it from the stream
#                 redis_consumer.xdel(generate_topic, message_id)
#
#
# def start_redis_consumer():
#     """
#     启动守护线程
#     """
#     t = threading.Thread(target=sub)
#     t.daemon = True
#     t.start()
#
#
# consumer = start_redis_consumer()
#
#
# # 创建一个生产者
# redis_product = redis.StrictRedis(**redis_conf)
#
#
# def redis_queue_send_message(data, topic=generate_topic):
#     """
#     发送消息
#     """
#     redis_product.xadd(topic, data)
#
#
# def get_redis_queue_length(topic=generate_topic):
#     """
#     获取队列长度
#     """
#     return redis_product.execute_command('XLEN', topic)
#
#

# # # --------------------------------------  处理消息  -----------------------------------------------------
# @database_close_old_connections
# def process_messages(message_data):
#     try:
#         generate_type = message_data.get('generate_type')
#         record_id = message_data.get('record_id')
#         if str(generate_type) == '1':
#             # 生成设计
#             img_path_list, seed_list = start_txt2img_req_generate(message_data)
#             process_txt2img_result(img_path_list, seed_list, record_id)
#
#         elif str(generate_type) == '3':
#             # 细节重绘
#             message_data['init_images'] = [message_data['init_images']]
#             img_path_list, seed_list = start_img2img_req_generate(message_data)
#             process_img2img_result(img_path_list, seed_list, record_id)
#     except Exception as e:
#         print('msg process fail!')
#         print(traceback.format_exc())
